<template>
  <!-- 首页新闻轮播图(避免页面抖动，使用非计算方式简单的轮播图组件替换a-carousel) -->
  <div class="NewsPlayer-container">
    <a-row
      type="flex"
      class="content-box"
      :style="itemList.length > 0 ? { marginLeft: `-${Number(activeIndex) * 100}%` } : {}"
    >
      <div class="content-wrapper" v-for="(item, index) in itemList" :key="item[itemKey]">
        <slot name="content" :data="item" :index="index"></slot>
      </div>
    </a-row>
    <ul class="dot-wrapper" :class="[dotsClass]">
      <li
        class="dot-item base-btn"
        @click.stop="onDotClick(index)"
        :class="[activeIndex === index ? 'active-dot' : '']"
        v-for="(item, index) in itemList"
        :key="index"
      ></li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'NewsPlayer',
  props: {
    itemList: {
      type: Array,
      default() {
        return []
      }
    },
    dotsClass: {
      type: String,
      default: ''
    },
    itemKey: {
      type: String,
      default: 'id'
    },
    autoPlay: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      activeIndex: 0
    }
  },
  beforeDestroy() {
    this.removeTimer()
  },
  watch: {
    itemList(e) {
      e?.length > 1 && !this.timer && this.handlePlay()
    }
  },
  methods: {
    /**
     * 点击指示器
     * @param {Number} index - 点击的序号
     */
    onDotClick(index) {
      this.activeIndex = index
      this.handlePlay()
    },
    removeTimer() {
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
    },
    /**
     * 处理自动播放逻辑
     */
    handlePlay() {
      if (!this.autoPlay) return
      const delay = 1000 * 6 // 切换间隔
      this.removeTimer()
      this.timer = setInterval(() => {
        const index = this.activeIndex + 1
        if (index >= this.itemList.length) {
          this.activeIndex = 0
        } else {
          this.activeIndex = index
        }
      }, delay)
    }
  }
}
</script>
<style lang="less" scoped>
.NewsPlayer-container {
  height: 100%;
  position: relative;
  overflow: hidden;
  margin-right: 16px;
  .content-box {
    transition: all 0.5s;
    width: 100%;
    flex-wrap: nowrap;
    .content-wrapper {
      width: 100%;
      flex-shrink: 0;
    }
  }
  .dot-wrapper {
    list-style: none;
    width: 100%;
    position: absolute;
    bottom: 15%;
    display: flex;
    padding: 0;
    justify-content: center;
    .dot-item {
      width: 12px;
      height: 3px;
      // border-radius: 50%;
      display: inline-block;
      margin: 0 2px;
      background: #fff;
      opacity: 0.3;
      transition: all 0.5s;
    }
    .active-dot {
      width: 20px;
      opacity: 1;
    }
  }
}
</style>